package cn.easyplatform.studio.web.views.impl;

import cn.easyplatform.studio.StudioApp;
import cn.easyplatform.studio.utils.AppServiceFileUtils;
import cn.easyplatform.studio.utils.FileUtil;
import cn.easyplatform.studio.utils.TemplateUtil;
import cn.easyplatform.studio.utils.WebUtils;
import cn.easyplatform.studio.web.editors.EditorCallback;
import org.apache.commons.io.FileUtils;
import org.zkoss.image.AImage;
import org.zkoss.util.resource.Labels;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zk.ui.event.UploadEvent;
import org.zkoss.zk.ui.util.Clients;
import org.zkoss.zul.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;



public class AppPageImageView extends AbstractView<String> {
    private Grid grid;

    //private TemplateVo template;
    private TemplateUtil.TemplateType templateType;

    private List<String> fileNameList;

    private Timer timer;

    private String pathName;

    /**
     * @param cb
     */
    protected AppPageImageView(EditorCallback<String> cb,String pathName,TemplateUtil.TemplateType templateType,
                               Component component) {
        super(component, cb);

        this.templateType = templateType;
        this.pathName = pathName;
        fileNameList = FileUtil.getFilePathWithDirectory(new AppServiceFileUtils().getFilePath(pathName,templateType) + "/img");
    }

    @Override
    protected void createContent(Component parent) {
        grid = new Grid();
        grid.setHflex("1");
        grid.setVflex("1");
        grid.setId("appPageImageView_grid_result");
        Rows rows = new Rows();

        Columns columns = new Columns();
        columns.setSizable(true);
        String[] titles = new String[]{"view.template.original.image", "view.template.current.image",
                "view.template.upload.image", "view.template.restore.image"};
        for (int index = 0; index < titles.length; index++) {
            Column column = new Column(Labels.getLabel(titles[index]));
            if (index < 2)
                column.setHflex("1");
            else
                column.setWidth("80px");
            column.setParent(columns);
        }
        columns.setParent(grid);


        for (int i = 0; i < fileNameList.size(); i ++) {
            Row row = new Row();

            Image originalImage = new Image();
            originalImage.setHeight("80px");
            originalImage.setStyle("margin:10% 10%");
            row.appendChild(originalImage);
            String currentPath = new AppServiceFileUtils().getFilePath(pathName,templateType) + "/img/";
            String currentImagePath = new AppServiceFileUtils().getFilePath(pathName,templateType) + "/img/" + fileNameList.get(i);
            String originalPath = new AppServiceFileUtils().getFilePath(pathName,templateType) + "/img/restore/";
            String originalImagePath = new AppServiceFileUtils().getFilePath(pathName,templateType) + "/img/restore/" + fileNameList.get(i);

            if (new File(originalImagePath).exists() == false) {
                FileUtil.mkdirForNoExists(originalPath);
                try {
                    FileUtil.copyDirInFile(currentPath, originalPath);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            try {
                originalImage.setContent(new AImage(fileNameList.get(i), new FileInputStream(
                        originalImagePath)));
            } catch (IOException e) {
                e.printStackTrace();
            }

            Image currentImage = new Image();
            currentImage.setHeight("80px");
            currentImage.setStyle("margin:10% 10%");
            row.appendChild(currentImage);
            try {
                currentImage.setContent(new AImage(fileNameList.get(i), new FileInputStream(
                        currentImagePath)));
            } catch (IOException e) {
                e.printStackTrace();
            }

            Button uploadBtn = new Button();
            uploadBtn.setVflex("1");
            uploadBtn.setUpload("true,maxsize=300");
            uploadBtn.setLabel(Labels.getLabel("view.template.upload.image"));
            row.appendChild(uploadBtn);

            Button restoreBtn = new Button();
            restoreBtn.setVflex("1");
            restoreBtn.setLabel(Labels.getLabel("view.template.restore.image"));
            row.appendChild(restoreBtn);

            new EventCell(fileNameList.get(i), currentImagePath, originalImagePath, currentImage, uploadBtn, restoreBtn);
            row.setParent(rows);
        }
        grid.appendChild(rows);
        grid.setParent(parent);
        timer = new Timer();
        timer.setDelay(4000);
        parent.getParent().getParent().appendChild(timer);
        timer.addEventListener(Events.ON_TIMER, this);
        timer.stop();
    }

    @Override
    public void onEvent(Event event) throws Exception {
        if (event.getTarget().equals(timer)) {
            Clients.clearBusy();
            timer.stop();
            if (cb != null)
                cb.setValue("");
        }
    }


    private class EventCell implements EventListener<Event> {

        private String nameStr;
        private String currentImagePath;
        private String originalImagePath;
        private Image currentImage;
        private Button uploadBtn;
        private Button restoreBtn;

        public EventCell(String nameStr, String currentImagePath, String originalImagePath, Image currentImage, Button uploadBtn, Button restoreBtn) {
            this.nameStr = nameStr;
            this.currentImagePath = currentImagePath;
            this.originalImagePath = originalImagePath;
            this.currentImage = currentImage;
            this.uploadBtn = uploadBtn;
            this.uploadBtn.addEventListener(Events.ON_UPLOAD, this);
            this.restoreBtn = restoreBtn;
            this.restoreBtn.addEventListener(Events.ON_CLICK, this);
        }

        @Override
        public void onEvent(Event event) throws Exception {
            if (event.getTarget().equals(uploadBtn)) {
                UploadEvent evt = (UploadEvent) event;
                org.zkoss.util.media.Media media = evt.getMedia();
                if (media instanceof org.zkoss.image.Image) {
                    org.zkoss.image.Image img = (org.zkoss.image.Image) media;
                    currentImage.setContent(img);
                    FileUtils.copyInputStreamToFile(media.getStreamData(), new File(currentImagePath));
                    Clients.showBusy(Labels.getLabel("entity.template.loading.message"));
                    timer.start();
                } else {
                    //Messagebox.show("Not an image: " + media, "Error", Messagebox.OK, Messagebox.ERROR);
                    WebUtils.showError(Labels.getLabel("file.upload.error"));
                }
            } else if (event.getTarget().equals(restoreBtn)) {
                try {
                    FileUtil.copyFileUsingFileChannels(new File(originalImagePath), new File(currentImagePath));
                    currentImage.setContent(new AImage(nameStr, new FileInputStream(
                            currentImagePath)));
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    Clients.showBusy(Labels.getLabel("entity.template.loading.message"));
                    timer.start();
                }
            }
        }
    }
}
